package com.steven.ourcontest.chat.view

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.chat.adapter.FriendListAdapter
import com.steven.ourcontest.chat.viewmodel.FriendViewModel
import kotlinx.android.synthetic.main.fragment_friends.*

class FriendsFragment : BaseFragment() {

    private val adapter by lazy {
        context?.let {
            FriendListAdapter(it) { uid ->
                AppRouter.openUserDetailActivity(it, uid)
            }
        }
    }
    private val friendViewModel: FriendViewModel by activityViewModels()

    override fun getViewId(): Int? = R.layout.fragment_friends

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
    }

    private fun initView() {
        rv_friends?.adapter = adapter
    }

    private fun initListener() {
        friendViewModel.queryFriendsResponse.observe(viewLifecycleOwner, Observer {
            if (it != null) {
                adapter?.apply {
                    listData.clear()
                    listData.addAll(it.data)
                    notifyDataSetChanged()
                }
            }
        })
        friendViewModel.queryFriends()
        cl_new_friends?.setOnClickListener {
            context?.let { it1 -> AppRouter.startNewFriendsActivity(it1) }
        }
        cl_chat_friends?.setOnClickListener {
            context?.let { it1 -> AppRouter.openChatFriendsHistoryActivity(it1) }
        }
    }

    override fun onResume() {
        super.onResume()
        friendViewModel.queryFriends()
    }
}